package org.jzyan.framework.delayedqueue.init;

import lombok.extern.slf4j.Slf4j;
import org.jzyan.framework.delayedqueue.RedisDelayedQueue;
import org.jzyan.framework.delayedqueue.listener.RedisDelayedQueueListener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <p>
 * 初始化队列监听
 * </p>
 *
 * @author jzyan
 * @since 2021-09-15
 */
@Slf4j
@Component
public class RedisDelayedQueueInit implements ApplicationContextAware {

    @Autowired
    private RedisDelayedQueue redisDelayedQueue;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, RedisDelayedQueueListener> map = applicationContext.getBeansOfType(RedisDelayedQueueListener.class);
        for (Map.Entry<String, RedisDelayedQueueListener> taskEventListenerEntry : map.entrySet()) {
            String listenerName = taskEventListenerEntry.getValue().getClass().getName();
            startThread(listenerName, taskEventListenerEntry.getValue());
        }
    }

    /**
     * 启动线程获取队列*
     *
     * @param queueName                 queueName
     * @param redisDelayedQueueListener 任务回调监听
     * @param <T>                       泛型
     * @return
     */
    private <T> void startThread(String queueName, RedisDelayedQueueListener redisDelayedQueueListener) {
        redisDelayedQueue.take(queueName, redisDelayedQueueListener);
    }

}
